package org.example.config;

import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;

public class SystemInfo {
    // 获取 CPU 使用情况
    public double getCPUUsage() {
        double cpuUsage = 0;
        try {
            MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();
            ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
            AttributeList list = mbsc.getAttributes(name, new String[]{"ProcessCpuLoad"});
            if (!list.isEmpty()) {
                Attribute att = (Attribute) list.get(0);
                Double value = (Double) att.getValue();
                if (value == -1) {
                    return 0;
                }
                cpuUsage = ((int) (value * 1000) / 10.0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cpuUsage;
    }

    // 获取系统内存使用情况
    public double getMemoryUsage() {
        double memoryUsage = 0;
        try {
            MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();
            ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
            AttributeList list = mbsc.getAttributes(name, new String[]{"TotalPhysicalMemorySize", "FreePhysicalMemorySize"});
            if (!list.isEmpty()) {
                long totalMemory = 0;
                long freeMemory = 0;
                Attribute att = (Attribute) list.get(0);
                totalMemory = Long.parseLong(att.getValue().toString());
                att = (Attribute) list.get(1);
                freeMemory = Long.parseLong(att.getValue().toString());
                memoryUsage = (totalMemory - freeMemory) * 100.0 / totalMemory;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return memoryUsage;
    }

    // 获取 JVM 使用情况
    public double getJVMUsage() {
        double jvmUsage = 0;
        try {
            Runtime runtime = Runtime.getRuntime();
            long totalMemory = runtime.totalMemory();
            long freeMemory = runtime.freeMemory();
            long usedMemory = totalMemory - freeMemory;
            jvmUsage = usedMemory * 100.0 / totalMemory;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jvmUsage;
    }
}
